import socket
import sys
import time
from selectors import DefaultSelector, EVENT_READ, EVENT_WRITE

selector = DefaultSelector()

times = 10


class Future:
    def __init__(self):
        self.coro = None

    def add_coro(self, coro):
        self.coro = coro

    def resume(self):
        global times
        try:
            self.coro.send(None)
        except StopIteration:
            times -= 1


def fetch():
    sock = socket.socket()
    sock.setblocking(False)
    try:
        sock.connect(('www.baidu.com', 80))
    except BlockingIOError:
        pass
    f = Future()

    selector.register(sock.fileno(), EVENT_WRITE, f.resume())
    yield f

    selector.unregister(sock.fileno())

    req = b'GET / HTTP/1.0\r\n Host:www.baidu.com\r\n\r\n'
    sock.send(req)

    selector.register(sock, EVENT_READ, f.resume())
    yield f
    selector.unregister(sock.fileno())

    data = sock.recv(1024)


def task():
    coro = fetch()
    future = coro.send(None)
    future.add_coro(coro)


def loop():
    while times:
        events = selector.select()
        for key, mask in events:
            callback = key.data
            callback()
            if times <= 0:
                break


if __name__ == '__main__':
    for i in range(times):
        task()
    loop()
